/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
/**
 * Software License, Version 1.0
 *
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 *
 *
 *Redistribution and use in source and binary forms, with or without
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For
 * further information contact the Community Grids Lab at
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and
 * wherever such third-party acknowledgments normally appear.
 *
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering,
 * shall not be used to endorse or promote products derived from this software
 * without prior written permission from Indiana University.  For written
 * permission, please contact the Advanced Research and Technology Institute
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering,
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 *
 *
 * Indiana University provides no reassurances that the source code provided
 * does not infringe the patent or any other intellectual property rights of
 * any other entity.  Indiana University disclaims any liability to any
 * recipient for claims brought by any other entity based on infringement of
 * intellectual property rights or otherwise.
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS.
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS",
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.transport.ptcp;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.SocketException;

import cgl.narada.protocol.Protocol;
import cgl.narada.transport.TransportDebugFlags;
import cgl.narada.transport.TransportException;
import cgl.narada.transport.ptcp.psocket.PTCPOutputStream;
import cgl.narada.transport.ptcp.psocket.PTCPSocket;

/**
   Responsible for sending tcp packets across the socket connection that is
   established during initializations. The TCPSenderThread notifies any loss
   of connections to the TCPLink which in turn proceeds to noitify the
   TCPLinkFactory.

   @author Shrideep Pallickara
   $Revision$
   $Date$
 */

public class PTCPSenderThread
    extends Thread
    implements TransportDebugFlags {
  private PTCPSocket psocket;
  private byte[] data;
  private DataOutputStream dout;
  private PTCPOutputStream pos;

  private PTCPLink ptcpLink;
  private int packetTracker = 0;
  private int lastPacketAcked = 0;

  private String moduleName = "PTCPSenderThread: ";

  public PTCPSenderThread(PTCPSocket psocket, PTCPLink ptcpLink) {
    this.psocket = psocket;
    this.ptcpLink = ptcpLink;
    try {
      if (!psocket.getTcpNoDelay()) {
        if (PTCPSenderThread_Debug) {
          System.out.println(moduleName + "Nagle's algorithm being disabled");
        }
        psocket.setTcpNoDelay(true);
      }
    }
    catch (SocketException se) {
      se.printStackTrace();
    }

    try {
      //dout = new DataOutputStream(psocket.getOutputStream());
      pos = (PTCPOutputStream) psocket.getOutputStream();
    }
    catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }

  public void releaseResources() {
    if (PTCPSenderThread_Debug) {
      System.out.println(moduleName + "Closing " + psocket);
    }
    try {
      psocket.getInputStream().close();
      psocket.close();
    }
    catch (IOException ioe) {
      System.out.println(moduleName + "Problem while releasing resources" +
                         ioe);
    }
  }

  public synchronized void sendData(byte[] dataToSend) throws
      TransportException {
    //I was here to update code
    if (PTCPSenderThread_Debug) {
      System.out.println(moduleName + "Sending data on link "
                         + ptcpLink.getLinkId());

    }
    try {
      if (!psocket.isConnected()) {
        throw new TransportException(moduleName +
                                     "PSocket no longer connected");
      }
      int dataLength = dataToSend.length;
      if (dataLength <= 0) {
        System.out.println("\n **PTCPSenderThread: Data length <= 0 *** \n");
        return;
      }

      packetTracker++;

      int numOfBytesToSend = 1 + 4 + dataLength;
      byte[] header = null;
      ByteArrayOutputStream thstream = new ByteArrayOutputStream(
          numOfBytesToSend);
      DataOutputStream headerStream = new DataOutputStream(thstream);

      try {
        headerStream.writeByte(Protocol.DATA);
        headerStream.writeInt(dataLength);
        headerStream.write(dataToSend, 0, dataLength);
      }
      catch (IOException e) {
        throw e;
      }

      header = thstream.toByteArray();

      if (header.length != numOfBytesToSend) {
        System.out.println("\n \n " + moduleName +
                           "dout.size() should have been" +
                           header.length +
                           "instead, dout.size()=" + numOfBytesToSend + "\n \n");
      }
      if (PTCPSenderThread_Debug && dataLength > 100000) {
        System.out.println(moduleName + "Flaggin data of size[" +
                           dataLength + "] ");
      }

      try {
        pos.send(header);
        pos.flush();
      }
      catch (Exception ex) {
        ex.printStackTrace();
      }

      if (PTCPSenderThread_Debug) {
        System.out.println(moduleName + ptcpLink.getLinkId() +
                           " socket.isOutputShutdown()" +
                           psocket.isOutputShutdown());
      }

      if (TCPSenderThread_Debug) {
        System.out.println(moduleName + ptcpLink.getLinkId() +
                           "dout.size() = " + numOfBytesToSend);
        System.out.println(moduleName + "Sent data on link " +
                           ptcpLink.getLinkId() + "PacketNumber=" +
                           packetTracker + " , size=" + dataLength);
      }
    }
    catch (java.io.IOException ioe) {
      String errorInfo = moduleName + "sending data " + ioe;
      System.out.println(errorInfo);
      throw new TransportException(errorInfo);
    }
  }

  public void sendData(byte[] dataToSend,
                       String dataType) throws TransportException {
    /** NBNI*/
    sendData(dataToSend);
  }

  public void sendPing() {
    //This will be fixed later
    /*
     try {
      dout.writeByte(Protocol.PING);
      dout.writeLong(System.currentTimeMillis());
      dout.flush();
         }
         catch (java.io.IOException ioe) {
      System.out.println("Lost connection to " + psocket);
         }
     */
  }

  public void sendPingResponse(long timeSent) {
    //This will be fixed later
    /*
         try {
      dout.writeByte(Protocol.PING_REPLY);
      dout.writeLong(timeSent);
      dout.flush();
         }
         catch (java.io.IOException ioe) {
      System.out.println("Lost connection to " + psocket);
         }
     */
  }

  public void run() {

  }

}
